package org.dreamwork.jasmine2.template.impl;

import org.dreamwork.jasmine2.template.ITemplateParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-4-2
 * Time: 13:45:11
 */
public class XMLTemplateParser implements ITemplateParser {
    protected Element root;

    public boolean validateTemplate (String content) {
        if (root != null) return true;
        try {
            parse (content);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public Element parse (String content) {
        if (root == null) try {
            DocumentBuilderFactory f = DocumentBuilderFactory.newInstance ();
            DocumentBuilder b = f.newDocumentBuilder ();
            Document d = b.parse (new InputSource (new StringReader (content)));
            root = d.getDocumentElement ();
            return root;
        } catch (Exception ex) {
            throw new RuntimeException (ex);
        }

        return root;
    }
}